package com.zh.kotlin_mvvm.ui

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.LogUtils
import com.zh.common.base.BaseActivity
import com.zh.common.ktx.inflate
import com.zh.kotlin_mvvm.R
import com.zh.kotlin_mvvm.databinding.ActivityViewPager2Binding

class ViewPager2Activity : BaseActivity<ActivityViewPager2Binding>() {

    private val myAdapter by lazy { MyAdapter() }
    override val statusBarColor = R.color.color_black

    override fun initView(savedInstanceState: Bundle?) {

        viewBinding.viewpager2.adapter = myAdapter
        viewBinding.viewpager2.offscreenPageLimit = 1
        viewBinding.viewpager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                myAdapter.mList.forEachIndexed { index, _ ->
                    if (index == position) {
                         //正在屏幕上
                    } else {
                        //不在屏幕上
                    }
                }
            }
        })
    }

    private inner class MyAdapter : RecyclerView.Adapter<MyAdapter.MyHolder>() {

        val mList = MutableList(20) { "1" }

        inner class MyHolder(itemView: View) : ViewHolder(itemView) {

        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
            return MyHolder(parent.context.inflate(R.layout.item_my, parent, false))
        }

        override fun getItemCount(): Int {
            return mList.size
        }

        override fun onBindViewHolder(holder: MyHolder, position: Int) {

        }

        override fun onViewAttachedToWindow(holder: MyHolder) {
            super.onViewAttachedToWindow(holder)
            val position = holder.absoluteAdapterPosition
            LogUtils.e("onViewAttachedToWindow--=$position")
            //添加到屏幕，这里做初始化操作

        }

        override fun onViewDetachedFromWindow(holder: MyHolder) {
            super.onViewDetachedFromWindow(holder)
            val position = holder.absoluteAdapterPosition
            LogUtils.e("onViewDetachedFromWindow--=$position")
            //移出屏幕，这里做销毁操作

        }
    }
}